package service

import (
	"context"
	"database/sql"
	"fx_swift_ifcgate/api"
	"fx_swift_ifcgate/internal/model"
	"fx_swift_ifcgate/pkg/code"
	"fx_swift_ifcgate/pkg/global"
	"fx_swift_ifcgate/pkg/internalerrors"
	"fx_swift_ifcgate/pkg/logger"
	"fx_swift_ifcgate/pkg/utils"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"strings"
)

type IMerchantVASrv interface {
	MerChantOnboard(ctx context.Context, req *api.MerChantVAReq) error
	CreateMerChantTemp(ctx context.Context, req *api.MerChantTempReq) error
	GetMerChantTemp(ctx context.Context, acct string) (*api.MerChantTempRes, error)
	QueryBusinessNature(ctx context.Context, natureType string) ([]*api.BusinessNatureRes, error)
	QuerySourceFund(ctx context.Context) ([]*api.SourceFundRes, error)
	QueryPaymentPurpose(ctx context.Context) ([]*api.PaymentPurposeRes, error)
	GetMerChantName(ctx context.Context) (*api.MerChantNameRes, error)
	QueryMerChantMessage(ctx context.Context) (*api.MerChantMessage, error)
	QueryTurnover(ctx context.Context) ([]*api.TurnoverRes, error)
	QueryTransaction(ctx context.Context) ([]*api.TransactionRes, error)
}

type merchantVASrv struct {
}

func NewMerchantVASrv() IMerchantVASrv {
	return &merchantVASrv{}
}

// 获取交易量
func (m merchantVASrv) QueryTransaction(ctx context.Context) ([]*api.TransactionRes, error) {
	var (
		err            error
		transactionObj []*model.IFCGateTransactionBase
	)
	if err = global.GFDB.Ctx(ctx).Model("ifcgate_transaction_base").Scan(&transactionObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}

	if transactionObj == nil {
		return []*api.TransactionRes{}, nil
	}

	result := make([]*api.TransactionRes, 0)
	for _, value := range transactionObj {
		result = append(result, &api.TransactionRes{
			Code: value.Code,
			Desc: value.Desc,
		})
	}
	return result, err
}

// 获取营业额
func (m merchantVASrv) QueryTurnover(ctx context.Context) ([]*api.TurnoverRes, error) {
	var (
		err         error
		turnoverObj []*model.IFCGateTurnover
	)
	if err = global.GFDB.Ctx(ctx).Model("ifcgate_turnover_base").Scan(&turnoverObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}

	if turnoverObj == nil {
		return []*api.TurnoverRes{}, nil
	}

	result := make([]*api.TurnoverRes, 0)
	for _, value := range turnoverObj {
		result = append(result, &api.TurnoverRes{
			Code: value.Code,
			Desc: value.Desc,
		})
	}
	return result, err
}

// 获取当前商户入网状态信息
func (m merchantVASrv) QueryMerChantMessage(ctx context.Context) (*api.MerChantMessage, error) {
	var (
		err             error
		merChantInfoObj *model.IFCGateMerChantVAInfo
		account         string
	)
	account = ctx.Value("Account").(string)
	if err = global.GFDB.Model("ifcgate_merchant_va_info").Where("account", account).Scan(&merChantInfoObj); err != nil {
		logger.SugarLogger.Error(err)
		return &api.MerChantMessage{}, internalerrors.New(code.ErrUnknown, err.Error())
	}
	if merChantInfoObj == nil {
		return &api.MerChantMessage{}, nil
	}

	return &api.MerChantMessage{
		Status:  merChantInfoObj.Status,
		Message: merChantInfoObj.Message,
	}, nil
}

// 获取账户持有人名称
func (m merchantVASrv) GetMerChantName(ctx context.Context) (*api.MerChantNameRes, error) {
	var (
		err             error
		merChantInfoObj *model.IFCGateMerChantVAInfo
		merChantNo      string
	)

	merChantNo = ctx.Value("MerchantNo").(string)
	if err = global.GFDB.Model("ifcgate_merchant_va_info").Where("merchant_no", merChantNo).Scan(&merChantInfoObj); err != nil {
		logger.SugarLogger.Error(err)
		return &api.MerChantNameRes{}, internalerrors.New(code.ErrUnknown, err.Error())
	}
	if merChantInfoObj == nil {
		return &api.MerChantNameRes{}, nil
	}

	return &api.MerChantNameRes{
		MerNameEn: merChantInfoObj.MerNameEn,
		MerNameCn: merChantInfoObj.MerNameCn,
	}, nil
}

// 获取付款目的
func (m merchantVASrv) QueryPaymentPurpose(ctx context.Context) ([]*api.PaymentPurposeRes, error) {
	var (
		err        error
		paymentObj []*model.IFCGatePaymentPurpose
	)
	if err = global.GFDB.Ctx(ctx).Model("ifcgate_payment_purpose_base").Scan(&paymentObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}

	if paymentObj == nil {
		return []*api.PaymentPurposeRes{}, nil
	}

	result := make([]*api.PaymentPurposeRes, 0)
	for _, value := range paymentObj {
		result = append(result, &api.PaymentPurposeRes{
			Code: value.Code,
			Desc: value.Desc,
		})
	}
	return result, err
}

// 获取资金来源
func (m merchantVASrv) QuerySourceFund(ctx context.Context) ([]*api.SourceFundRes, error) {
	var (
		err           error
		sourceFundObj []*model.IFCGateSourceFund
	)
	if err = global.GFDB.Ctx(ctx).Model("ifcgate_source_funds_base").Scan(&sourceFundObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "查询数据报错")
	}
	if sourceFundObj == nil {
		return []*api.SourceFundRes{}, nil
	}

	result := make([]*api.SourceFundRes, 0)
	for _, value := range sourceFundObj {
		result = append(result, &api.SourceFundRes{
			Code: value.Code,
			Desc: value.Desc,
		})
	}
	return result, err
}

// 获取业务性质
func (m merchantVASrv) QueryBusinessNature(ctx context.Context, natureType string) ([]*api.BusinessNatureRes, error) {
	var (
		err       error
		natureObj []*model.IFCGateNature
	)
	if natureType == "" {
		return nil, internalerrors.New(code.ErrUnknown, "业务性质类型不能为空")
	}

	if err = global.GFDB.Ctx(ctx).Model("ifcgate_nature_base").Where("nature_type", natureType).Scan(&natureObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "查询数据报错")
	}
	if natureObj == nil {
		return []*api.BusinessNatureRes{}, nil
	}

	result := make([]*api.BusinessNatureRes, 0)
	for _, value := range natureObj {
		result = append(result, &api.BusinessNatureRes{
			Code: value.Code,
			Desc: value.Desc,
		})
	}
	return result, err
}

// 获取KYF认证资料
func (m merchantVASrv) GetMerChantTemp(ctx context.Context, acct string) (*api.MerChantTempRes, error) {
	var (
		err        error
		account    string
		reqJsonObj *model.IFCGATEMerChantVATmp
	)

	account = acct
	if account == "" {
		account = ctx.Value("Account").(string)
	}

	if err = global.GFDB.Ctx(ctx).Model("ifcgate_merchant_va_tmp").Where("account=?", account).
		Scan(&reqJsonObj); err != nil {
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}
	if reqJsonObj == nil {
		return &api.MerChantTempRes{}, nil
	}

	return &api.MerChantTempRes{
		Account: reqJsonObj.Account,
		ReqJson: reqJsonObj.ReqJson,
	}, nil
}

// KYF认证资料临时存储
func (m merchantVASrv) CreateMerChantTemp(ctx context.Context, req *api.MerChantTempReq) error {
	var (
		err        error
		reqJsonObj *model.IFCGATEMerChantVATmp
		result     sql.Result
		rowsNums   int64
		account    string
	)
	account = ctx.Value("Account").(string)
	if err = global.GFDB.Model("ifcgate_merchant_va_tmp").Where("account", account).Scan(&reqJsonObj); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	if reqJsonObj == nil {
		result, err = global.GFDB.Insert(ctx, "ifcgate_merchant_va_tmp", &model.IFCGATEMerChantVATmp{
			Account:   account,
			ReqJson:   req.ReqJson,
			ReqBackup: req.ReqBackup,
		})

		if err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "kyc认证资料写入异常")
		}
		rowsNums, err = result.RowsAffected()
		if err != nil || rowsNums == 0 {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "kyc认证资料写入异常")
		}
	} else {
		if req.ReqJson != "" {
			result, err = global.GFDB.Ctx(ctx).Model("ifcgate_merchant_va_tmp").
				Data(g.Map{"req_json": req.ReqJson}).Where("account=?", account).Update()
		} else {
			result, err = global.GFDB.Ctx(ctx).Model("ifcgate_merchant_va_tmp").
				Data(g.Map{"req_backup": req.ReqBackup}).Where("account=?", account).Update()
		}

	}

	if err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, "kyc认证资料更新异常")
	}
	rowsNums, err = result.RowsAffected()
	if err != nil || rowsNums == 0 {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, "kyc认证资料更新异常")
	}

	return err
}

// 商户入网和VA开户
func (m merchantVASrv) MerChantOnboard(ctx context.Context, req *api.MerChantVAReq) error {
	var (
		//resStr      []byte
		merOrderNo  string
		err         error
		merchantObj *model.IFCGateMerChantVAInfo
	)

	var account = ctx.Value("Account").(string)
	if err = global.GFDB.Model("ifcgate_merchant_va_info").
		Where("account=?", account).Scan(&merchantObj); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if merchantObj == nil {
		merOrderNo = utils.GenerateCode64()
	} else {
		if merchantObj.MerchantNo != "" {
			return internalerrors.New(code.ErrUnknown, "该账号已有商户认证")
		}
		merOrderNo = merchantObj.MerOrderNo
		bizFlow := merchantObj.BizFlow
		req.BizFlow = bizFlow
	}
	req.MerOrderNo = merOrderNo
	req.ReferralChannel = global.ViperObj.GetString("ottpay.referralChannel")
	req.CallBackUrl = global.ViperObj.GetString("callback.merCallBackUrl")

	//converReq, err := ConvertMerChantReq(req)
	//if converReq == nil {
	//	return internalerrors.New(code.ErrUnknown, err.Error())
	//}
	////请求ottpay入网接口并提交参数
	//body, _ := json.Marshal(converReq)
	//resStr, err = OperatorParamToPost("tp1020", "", body)
	//if err != nil {
	//	logger.SugarLogger.Error(err)
	//	return internalerrors.New(code.ErrUnknown, err.Error())
	//}
	////返回结果集解析
	//resObj := &api.MerChantVARes{}
	//err = json.Unmarshal(resStr, &resObj)
	//if err != nil {
	//	logger.SugarLogger.Error(err)
	//	return internalerrors.New(code.ErrUnknown, err.Error())
	//}
	//
	////对kyc资料进行临时备份，以便入库失败进行补数据
	//req.BizFlow = resObj.MerchantVABody.BizFlow
	////tmpStr, _ := json.Marshal(req)
	//merChanTmp := &api.MerChantTempReq{
	//	ReqBackup: req.BizFlow,
	//}
	//err = m.CreateMerChantTemp(ctx, merChanTmp)
	//if err != nil {
	//	logger.SugarLogger.Error("kyc资料备份失败", err)
	//}
	/***
	1、子表信息入库
	2、商户入网资料表
	*/
	//交易模式表入库
	db := g.DB()
	err = db.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		if len(req.Transaction) != 0 {
			transList := []*model.IFCGateTransaction{}
			for _, transaction := range req.Transaction {
				transObj := &model.IFCGateTransaction{}
				transObj.MerOrderNo = merOrderNo
				transObj.TradeOption = transaction.TradeOption
				transObj.Country = transaction.Country
				transObj.TradeType = transaction.TradeType
				transList = append(transList, transObj)
			}
			//先删除
			result, err := global.GFDB.Model("ifcgate_transaction").Where("mer_order_no", req.MerOrderNo).Delete()
			if err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "transtion资料删除失败")
			}
			//后插入
			result, err = tx.Model("ifcgate_transaction").Data(transList).Insert()

			if err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "transtion资料插入失败")
			}
			rowsNums, err := result.RowsAffected()
			if err != nil || rowsNums == 0 {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "transtion资料插入失败")
			}
		}

		//reMaterial表入库
		if !utils.IsEmptyStruct(req.ReMaterial) {
			reMaterialList := []*model.IFCGateReMaterial{}
			reMaterialObj := &model.IFCGateReMaterial{}
			reMaterialObj.MerOrderNo = merOrderNo
			reMaterialObj.FinancialStatements = strings.Join(req.ReMaterial.FinancialStatements, ";")
			reMaterialObj.Questionnaire = strings.Join(req.ReMaterial.Questionnaire, ";")
			var bcStrAll []string
			for _, bestCustomer := range req.ReMaterial.BestCustomer {
				bcStr := bestCustomer.Name + "|" + bestCustomer.Country
				bcStrAll = append(bcStrAll, bcStr)
			}
			reMaterialObj.BestCustomer = strings.Join(bcStrAll, ";")

			var bpStrAll []string
			for _, bestPartner := range req.ReMaterial.BestPartner {
				bcStr := bestPartner.Name + "|" + bestPartner.Country
				bpStrAll = append(bpStrAll, bcStr)
			}
			reMaterialObj.BestPartner = strings.Join(bpStrAll, ";")
			reMaterialList = append(reMaterialList, reMaterialObj)

			//先删除
			result, err := global.GFDB.Model("ifcgate_re_material").Where("mer_order_no", req.MerOrderNo).Delete()
			if err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "reMaterial资料删除失败")
			}
			//后插入
			result, err = tx.Model("ifcgate_re_material").Data(reMaterialList).Insert()

			if err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "reMaterial资料插入失败")
			}
			rowsNums, err := result.RowsAffected()
			if err != nil || rowsNums == 0 {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "reMaterial资料插入失败")
			}
		}

		//personalInfo表入库
		personalList := []*model.IFCGatePersonalInfo{}
		//被授权人信息 3
		if len(req.Customer) != 0 {
			for _, customer := range req.Customer {
				personalObj := &model.IFCGatePersonalInfo{}
				personalObj.MerOrderNo = merOrderNo
				personalObj.PersonalType = "3"
				personalObj.Type = customer.Type
				personalObj.Name = customer.Name
				personalObj.IssuPlace = customer.IssuPlace
				personalObj.Nationality = customer.Nationality
				personalObj.IdNumber = customer.IdNumber
				personalObj.BirthDate = customer.BirthDate
				personalObj.CertificateDate = customer.CertificateDate
				personalObj.ResidenceCountry = customer.ResidenceCountry
				personalObj.Address = customer.Address
				if customer.Certificates != nil {
					personalObj.Certificates = strings.Join(customer.Certificates, ";")
				}

				personalList = append(personalList, personalObj)
			}
		}

		//持股25%以上股东	2
		if len(req.Shareholder) != 0 {
			for _, shareHolder := range req.Shareholder {
				personalObj := &model.IFCGatePersonalInfo{}
				personalObj.MerOrderNo = merOrderNo
				personalObj.PersonalType = "2"
				personalObj.Type = shareHolder.Type
				personalObj.Name = shareHolder.Name
				personalObj.IssuPlace = shareHolder.IssuPlace
				personalObj.Nationality = shareHolder.Nationality
				personalObj.IdNumber = shareHolder.IdNumber
				personalObj.BirthDate = shareHolder.BirthDate
				personalObj.CertificateDate = shareHolder.CertificateDate
				personalObj.ResidenceCountry = shareHolder.ResidenceCountry
				personalObj.Address = shareHolder.Address
				if shareHolder.Certificates != nil {
					personalObj.Certificates = strings.Join(shareHolder.Certificates, ";")
				}

				personalList = append(personalList, personalObj)
			}
		}

		//公司董事 1
		if len(req.Director) != 0 {
			for _, director := range req.Director {
				personalObj := &model.IFCGatePersonalInfo{}
				personalObj.MerOrderNo = merOrderNo
				personalObj.PersonalType = "1"
				personalObj.Type = director.Type
				personalObj.Name = director.Name
				personalObj.IssuPlace = director.IssuPlace
				personalObj.Nationality = director.Nationality
				personalObj.IdNumber = director.IdNumber
				personalObj.BirthDate = director.BirthDate
				personalObj.CertificateDate = director.CertificateDate
				personalObj.ResidenceCountry = director.ResidenceCountry
				personalObj.Address = director.Address
				personalObj.Certificates = strings.Join(director.Certificates, ";")

				personalList = append(personalList, personalObj)
			}
		}

		//法人 0
		if len(req.LegalPerson) != 0 {
			for _, legaPerson := range req.LegalPerson {
				personalObj := &model.IFCGatePersonalInfo{}
				personalObj.MerOrderNo = merOrderNo
				personalObj.PersonalType = "0"
				personalObj.Type = legaPerson.Type
				personalObj.Name = legaPerson.Name
				personalObj.IssuPlace = legaPerson.IssuPlace
				personalObj.Nationality = legaPerson.Nationality
				personalObj.IdNumber = legaPerson.IdNumber
				personalObj.BirthDate = legaPerson.BirthDate
				personalObj.CertificateDate = legaPerson.CertificateDate
				personalObj.ResidenceCountry = legaPerson.ResidenceCountry
				personalObj.Address = legaPerson.Address
				if legaPerson.Certificates != nil {
					personalObj.Certificates = strings.Join(legaPerson.Certificates, ";")
				}

				personalList = append(personalList, personalObj)
			}
			if personalList != nil {
				//先删除
				result, err := global.GFDB.Model("ifcgate_personal_info").Where("mer_order_no", req.MerOrderNo).Delete()
				if err != nil {
					logger.SugarLogger.Error(err)
					return internalerrors.New(code.ErrUnknown, "personalInfo资料删除失败")
				}
				//后插入
				result, err = tx.Model("ifcgate_personal_info").Data(personalList).Insert()

				if err != nil {
					logger.SugarLogger.Error(err)
					return internalerrors.New(code.ErrUnknown, "personalInfo资料插入失败")
				}
				rowsNums, err := result.RowsAffected()
				if err != nil || rowsNums == 0 {
					logger.SugarLogger.Error(err)
					return internalerrors.New(code.ErrUnknown, "personalInfo资料插入失败")
				}
			}

		}

		//VaInfo表入库
		if len(req.VaInfo) != 0 {
			vaInfoList := []*model.IFCGateVaInfo{}
			for _, vaInfo := range req.VaInfo {
				vaInfoObj := &model.IFCGateVaInfo{}
				vaInfoObj.MerOrderNo = merOrderNo
				vaInfoObj.ParentCode = vaInfo.ParentCode
				vaInfoObj.ApplyCode = vaInfo.ApplyCode
				vaInfoObj.Area = vaInfo.Area
				vaInfoObj.Currency = vaInfo.Currency
				vaInfoObj.AcctSimpleName = vaInfo.AcctSimpleName
				vaInfoObj.BankType = vaInfo.BankType
				vaInfoObj.ShopName = vaInfo.ShopName
				vaInfoObj.ShopUrl = vaInfo.ShopUrl
				vaInfoObj.CollectType = vaInfo.CollectType
				vaInfoObj.CollectName = vaInfo.CollectName
				vaInfoObj.WebSiteUrl = vaInfo.WebSiteUrl
				vaInfoObj.IsSameName = vaInfo.IsSameName
				vaInfoObj.BusDesDocument = strings.Join(vaInfo.BusDesDocument, ";")
				vaInfoObj.StoreHoldCertify = strings.Join(vaInfo.StoreHoldCertify, ";")
				vaInfoObj.CallBackUrl = global.ViperObj.GetString("callback.vaCallBackUrl")
				vaInfoObj.OtherPath = vaInfo.OtherPath
				vaInfoObj.Postscript = vaInfo.Postscript

				vaInfoList = append(vaInfoList, vaInfoObj)
			}
			//先删除
			result, err := global.GFDB.Model("ifcgate_va_info").Where("mer_order_no", req.MerOrderNo).Delete()
			if err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "vaInfo资料删除失败")
			}
			//后插入
			result, err = tx.Model("ifcgate_va_info").Data(vaInfoList).Insert()

			if err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "vaInfo资料插入失败")
			}
			rowsNums, err := result.RowsAffected()
			if err != nil || rowsNums == 0 {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "vaInfo资料插入失败")
			}

		}

		//商户入网资料表入库
		if req != nil {
			merchantVAObj := &model.IFCGateMerChantVAInfo{}
			merchantVAObj.MerOrderNo = merOrderNo
			merchantVAObj.BizFlow = req.BizFlow
			merchantVAObj.MerchantNo = ""
			merchantVAObj.AuthorizeCode = ""
			merchantVAObj.Email = req.Email
			merchantVAObj.PhoneAreaCode = req.PhoneAreaCode
			merchantVAObj.PhoneNum = req.PhoneNum
			merchantVAObj.ReferralChannel = req.ReferralChannel
			merchantVAObj.CountryCode = req.CountryCode
			merchantVAObj.MerNameEn = req.MerNameEn
			merchantVAObj.MerNameCn = req.MerNameCn
			merchantVAObj.EstablishDate = req.EstablishDate
			merchantVAObj.BrExpiryDate = req.BrExpiryDate
			merchantVAObj.RegistrationAddress = req.RegistrationAddress
			if req.EnterprisePath != nil {
				merchantVAObj.EnterprisePath = strings.Join(req.EnterprisePath, ";")
			}
			merchantVAObj.ParentRemark = req.ParentRemark
			if req.OwnerShipPath != nil {
				merchantVAObj.OwnerShipPath = strings.Join(req.OwnerShipPath, ";")
			}
			if req.ParentCertificate != nil {
				merchantVAObj.ParentCertificate = strings.Join(req.ParentCertificate, ";")
			}
			if req.ParentCompany != nil {
				var pcStrAll []string
				for _, parentCompany := range req.ParentCompany {
					pcStr := parentCompany.Name + "|" + parentCompany.Country
					pcStrAll = append(pcStrAll, pcStr)
				}
				merchantVAObj.ParentCompany = strings.Join(pcStrAll, ";")
			}

			merchantVAObj.BranchRemark = req.BranchRemark
			if req.BranchCompany != nil {
				var bcStrAll []string
				for _, branchCompany := range req.BranchCompany {
					bcStr := branchCompany.Name + "|" + branchCompany.Country
					bcStrAll = append(bcStrAll, bcStr)
				}
				merchantVAObj.BranchCompany = strings.Join(bcStrAll, ";")
			}
			if req.Certificate != nil {
				merchantVAObj.Certificate = strings.Join(req.Certificate, ";")
			}
			if req.CompanyCertificate != nil {
				merchantVAObj.CompanyCertificate = strings.Join(req.CompanyCertificate, ";")
			}

			merchantVAObj.CertificateNumber = req.CertificateNumber
			if req.ParticipantsType != nil {
				merchantVAObj.ParticipantsType = strings.Join(req.ParticipantsType, ";")
			}
			if req.Nnc1Path != nil {
				merchantVAObj.Nnc1Path = strings.Join(req.Nnc1Path, ";")
			}
			if req.Nar1Path1 != nil {
				merchantVAObj.Nar1Path1 = strings.Join(req.Nar1Path1, ";")
			}
			if req.AddressMaterial != nil {
				merchantVAObj.AddressMaterial = strings.Join(req.AddressMaterial, ";")
			}
			if req.Mermorandum != nil {
				merchantVAObj.Mermorandum = strings.Join(req.Mermorandum, ";")
			}

			if req.CustomerIdentity != nil {
				merchantVAObj.CustomerIdentity = strings.Join(req.CustomerIdentity, ";")
			}

			if req.Authorization != nil {
				merchantVAObj.Authorization = strings.Join(req.Authorization, ";")
			}

			if req.SourceFunds != nil {
				merchantVAObj.SourceFunds = strings.Join(req.SourceFunds, ";")
			}

			if req.PaymentPurpose != nil {
				merchantVAObj.PaymentPurpose = strings.Join(req.PaymentPurpose, ";")
			}
			merchantVAObj.RiskCountryTransaction = req.RiskCountryTransaction
			if req.RiskCountries != nil {
				var rcStrAll []string
				for _, riskCountry := range req.RiskCountries {
					rcStr := riskCountry.Name + "|" + riskCountry.Country
					rcStrAll = append(rcStrAll, rcStr)
				}
				merchantVAObj.RiskCountries = strings.Join(rcStrAll, ";")
			}

			merchantVAObj.AddMaterial = req.AddMaterial
			merchantVAObj.AddressType = req.AddressType
			merchantVAObj.CompanyWebsite = req.CompanyWebsite
			if req.ClientCountry != nil {
				merchantVAObj.ClientCountry = strings.Join(req.ClientCountry, ";")
			}

			if req.BusinessCountry != nil {
				merchantVAObj.BusinessCountry = strings.Join(req.BusinessCountry, ";")
			}

			if req.SuppliersCountry != nil {
				merchantVAObj.SuppliersCountry = strings.Join(req.SuppliersCountry, ";")
			}

			if req.InCountry != nil {
				merchantVAObj.InCountry = strings.Join(req.InCountry, ";")
			}

			if req.OutCountry != nil {
				merchantVAObj.OutCountry = strings.Join(req.OutCountry, ";")
			}

			merchantVAObj.LastYearTurnover = req.LastYearTurnover
			merchantVAObj.TransactionAmount = req.TransactionAmount
			merchantVAObj.WebSiteOrApp = req.WebSiteOrApp
			if !utils.IsEmptyStruct(req.BusinessNature) {
				merchantVAObj.BusinessNature = req.BusinessNature.NatureType + "|" + strings.Join(req.BusinessNature.Natures, ";")
			}
			merchantVAObj.NoticeMarker = req.NoticeMarker
			merchantVAObj.CallBackUrl = req.CallBackUrl
			if req.OtherPath != "" {
				merchantVAObj.OtherPath = req.OtherPath
			}

			merchantVAObj.Postscript = req.Postscript
			merchantVAObj.VaFlag = req.VaFlag
			var status = "APPROVAL"
			var message = ""
			if merchantObj != nil {
				//	status = "PENDING"
				message = merchantObj.Message
			}
			merchantVAObj.Status = status
			merchantVAObj.Message = message
			merchantVAObj.Account = ctx.Value("Account").(string)

			merchantVAList := []*model.IFCGateMerChantVAInfo{}
			merchantVAList = append(merchantVAList, merchantVAObj)

			//先删除
			result, err := global.GFDB.Model("ifcgate_merchant_va_info").Where("mer_order_no", req.MerOrderNo).Delete()
			if err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "商户入网资料删除失败")
			}
			//后插入
			result, err = tx.Model("ifcgate_merchant_va_info").Data(merchantVAList).Insert()

			if err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "商户入网资料插入失败")
			}
			rowsNums, err := result.RowsAffected()
			if err != nil || rowsNums == 0 {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "商户入网资料插入失败")
			}
		}
		return nil
	})

	if err != nil {

		logger.SugarLogger.Error("商户入网事务执行出错", err)
	} else {
		logger.SugarLogger.Info("商户入网事务执行成功")
	}

	return nil
}
